/**
 * @description 日志管理类
 *
 * @author Brave Chan on 2021.3
 *
 */
//===============================================
import be_opt from '../constant/be_opt';
//==============================================
const levels = {
  NORMAL: 0,
  INFO: 1,
  ERROR: 2,
  WARN: 3
};

let _logList = [];
/**
 * @internal
 * @description 格式化时间
 * @param {Number} num [required] 从1970.1.1至今的毫秒数
 * @param {Boolean} limit 是否只返回y-m-d的形式
 * @param {Boolean} noSecond 是否取出时分秒
 * @returns {String} 时间格式
 */
function formatTime(num, limit = true, noSecond = false) {
  if (typeof num !== 'number' || !Number.isInteger(+num)) {
    return num;
  }
  const date = new Date(num);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  const ymd = [year, month, day].map(formatNumber).join('-');
  if (limit) {
    return ymd;
  }

  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  let list = [hour, minute, second];
  if (noSecond) {
    list = list.slice(0, list.length - 1);
  }

  return ymd + ' ' + list.map(formatNumber).join(':')
}

/**
 * @internal
 * @description 格式化分秒数字
 * @param {Number} n [required] 数字
 * @returns {String} 格式化后的数字
 */
function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}
//===============================================
/**
 * 日志单项
 */
class LogItem {
  constructor(level, message, detail) {
    this.level = level;
    this.message = message;
    this.detail = detail;
    let timeNum = Date.now();
    this.time = formatTime(timeNum, false);
    this.id = `${timeNum}_${Math.random()}`;
  }
}
//================================================

//================================================
/**
 *  @public
 *
 * 输出普通日志
 */
function trace(...args) {
  _logList[_logList.length] = new LogItem(levels.NORMAL, '消息', args);
  if (be_opt.debug) {
    console.log.apply(console, args);
  }
}
/**
 *  @public
 *
 * 输出信息日志
 */
function info(...args) {
  _logList[_logList.length] = new LogItem(levels.INFO, '信息', args);
  if (be_opt.debug) {
    console.info.apply(console, args);
  }
}
/**
 *  @public
 *
 * 输出错误日志
 */
function error(...args) {
  _logList[_logList.length] = new LogItem(levels.ERROR, '错误', args);
  if (be_opt.debug) {
    console.error.apply(console, args);
  }
}
/**
 * @public
 *
 * 输出警告日志
 */
function warn(...args) {
  _logList[_logList.length] = new LogItem(levels.WARN, '警告', args);
  if (_debug) {
    console.warn.apply(console, arguments);
  }
}
//==========================================
export default {
  log: trace,
  trace,
  info,
  error,
  warn,
  /**
   * 获取日志信息列表
   */
  get logList() {
    return _logList;
  },
  clear() {
    _logList = [];
  },
  /**
   * @internal
   * 进行销毁LogManager的操作
   */
  destroy() {
    _logList = null;
  },
};
